<?php

namespace yan\backendclient\modules\role\models;

use Yii;

use yii\helpers\ArrayHelper;
/**
 * This is the model class for table "{{%backend_role_item}}".
 *
 * @property string $name
 * @property integer $type
 * @property string $description
 * @property string $rule_name
 * @property resource $data
 * @property integer $created_at
 * @property integer $updated_at
 */
class BackendRoleItem extends \yii\db\ActiveRecord
{
    public $route;

    public $method;

    public $group;

    public $category;

    public $sort;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%backend_role_item}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['route', 'method', 'description', 'group', 'category'], 'required', 'on' => 'permission'],
            [['sort'], 'number', 'on'=>['permission']],
            [['sort'], 'default', 'value'=>0, 'on'=>['permission']],

            [['name', 'type'], 'required'],
            [['type', 'created_at', 'updated_at'], 'integer'],
            [['description', 'data'], 'string'],
            [['name', 'rule_name'], 'string', 'max' => 64],
        ];
    }

    public function scenarios()
    {
        return [
            'permission' => ['route', 'method', 'description', 'sort', 'group', 'category'],
        ];
    }
    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'name' => Yii::t('debug', 'Name'),
            'type' => Yii::t('debug', 'Type'),
            'description' => Yii::t('debug', 'Description'),
            'rule_name' => Yii::t('debug', 'Rule Name'),
            'data' => Yii::t('debug', 'Data'),
            'created_at' => Yii::t('debug', 'Created At'),
            'updated_at' => Yii::t('debug', 'Updated At'),
            "route" => Yii::t('debug', 'Route'),
            "method" => Yii::t('debug', 'HTTP Method'),
            "description" => Yii::t('debug', 'Description'),
            "group" => Yii::t('debug', 'Group'),
            "category" => Yii::t('debug', 'Category'),
            "sort" => Yii::t('debug', 'Sort'),
            "name" => Yii::t('debug', 'Role'),
            "permissions" => Yii::t('debug', 'Permissions'),
            "roles" => Yii::t('debug', 'Role'),
        ];
    }
    // 行為
    public function behaviors()
    {

        $data = \yii\helpers\ArrayHelper::merge(parent::behaviors(), [
            'timestamp' => [
                'class' => 'yii\behaviors\TimestampBehavior',
                'attributes' => [
                    \yii\db\ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
                    \yii\db\ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
                ],
            ]
        ]);
        return $data;
    }

    public function getGroups()
    {
        $temp = $this->getPermissionsByGroup();
        $groups = [];
        foreach ($temp as $v){
            $groups[$v->group] = $v->group;
        }
        return $groups;
    }

    public function getCategories()
    {
        $temp = $this->getPermissionsByGroup();
        $categories = [];
        foreach ($temp as $v){
            $categories[$v->category] = $v->category;
        }
        return $categories;
    }
    public function getPermissionsByGroup($type='index')
    {

        $fillDatas = [];
        $originPermissions = BackendRoleItem::find()->all();

        $permissions = [];
        foreach ($originPermissions as $originPermission){
            $data = json_decode($originPermission->data, true);
            $temp = explode(":", $originPermission->name);
            $permissions[] = [
                'name' => $originPermission->name,
                'route' => $originPermission->name,
                'method' => $data['method'],
                'description' => $originPermission->description,
                'group' => $data['group'],
                'category' => $data['category'],
                'sort' => $data['sort'],
            ];
        }
        ArrayHelper::multisort($permissions, 'sort');
        foreach ($permissions as $permission){
            $fillDatas[$permission['group']][$permission['category']][] = $permission;
        }
        $return = [];
        if( $type == 'index' ){
            foreach ($fillDatas as $value){
                foreach ($value as $val) {
                    foreach ($val as $v) {
                        $return[] = new self(array_merge($v, ['scenario' => 'role']));
                    }
                }
            }
        }else{
            $return = $fillDatas;
        }
        return $return;
    }

    public function createPermission()
    {
        $this->name = $this->route;// . ':' . $this->method;

        if (static::findOne($this->name) !== null) {
            $this->addError('route', Yii::t('debug', 'Permission exists'));
            $this->addError('method', Yii::t('debug', 'Permission exists'));
            return false;
        }
        $this->type = 2;
        $this->data = json_encode([
            'group' => $this->group,
            'sort' => $this->sort,
            'category' => $this->category,
            'method' => $this->method,
        ]);
        return $this->save();
        // return false;
    }
    public function updatePermission($name)
    {
        $this->name = $this->route;
        if( $this->name != $name ){//修改权限名称
            if (static::findOne($this->name) !== null) {
                $this->addError('route', Yii::t('debug', 'Permission exists'));
                $this->addError('method', Yii::t('debug', 'Permission exists'));
                return false;
            }
        }
        $this->data = json_encode([
            'group' => $this->group,
            'sort' => $this->sort,
            'category' => $this->category,
            'method' => $this->method,
        ]);

        return $this->save();
    }
    public function fillModel(){
        $data = json_decode($this->data, true);
        $temp = explode(":", $this->name);
        $this->name = $this->name;
        $this->route = $this->name;
        $this->method = $data['method'];
        // $this->description = $permission->description;
        $this->group = $data['group'];
        $this->category = isset( $data['category'] ) ? $data['category'] : '';
        $this->sort = $data['sort'];
    }
}
